# -*- coding: utf-8 -*-

from omniORB import CORBA, PortableServer
import CosNaming
import sys

import lsh,lsh__POA

import os
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.neighbors import LSHForest

class LshImpl(lsh__POA.Lsh):
    file_title = 'title.txt'
    file_dic = 'english_stopword.dic'

    def __init__(self):
        dic_key = []
        dic_value = []
        word_stop_dic = {}

        with open(self.file_dic) as f1:
            for line in f1:
                line = line.strip()
                dic_key.append(line)

        dic_value = [0 for x in range(len(dic_key))]
        word_stop_dic = dict(zip(dic_key, dic_value))

        self.raw_document = []
        with open(self.file_title) as f1:
            for line in f1:
                line = line.split(' ', 2)
                self.raw_document.append(line)

        self.tfidf_vectorizer = TfidfVectorizer(min_df=3, max_features=None, ngram_range=(1, 2), use_idf=1, smooth_idf=1,
                                           sublinear_tf=1)
        train_document = []

        for item in self.raw_document:
            item_word = self.split_sentence(item[2])
            new_text = []
            for word in item_word:
                if word not in word_stop_dic:
                    new_text.append(word)
            newtext = ' '.join(new_text)
            train_document.append(newtext)

        x_train = self.tfidf_vectorizer.fit_transform(train_document)

        self.lshf = LSHForest(min_hash_match=4, n_candidates=50, n_estimators=50, \
                         n_neighbors=3, radius=1.0, radius_cutoff_ratio=0.5, \
                         random_state=42)
        self.lshf.fit(x_train.toarray())


    @staticmethod
    def split_sentence(word):
        word = word.split()
        return word

    def candidate(self,query):
        print query
        x_test = self.tfidf_vectorizer.transform([query])
        distances, indices = self.lshf.kneighbors(x_test.toarray(), n_neighbors=300)

        idList = []
        i = 0
        j = 0
        for v in indices:
            for u in v:
                if (distances[i][j] >= 0.95 and j > 20):
                    continue
                print(self.raw_document[u][0] + ' ' + self.raw_document[u][1] + ' ' + str(1 - distances[i][j]) + '\n')
                pair = lsh.Lsh.Pair(int(self.raw_document[u][0]),int(self.raw_document[u][1]),1 - distances[i][j])
                # idList.append(int(self.raw_document[u][1]))
                idList.append(pair)
                j = j + 1
            i = i + 1
            j = 0
        return idList


if __name__ == '__main__':
    # 创建一个ORB实例
    sys.argv.extend(("-ORBInitRef", "NameService=corbaloc::localhost:6666/NameService"))
    orb = CORBA.ORB_init(sys.argv, CORBA.ORB_ID)

    # 拿到RootPOA的引用，并激活POAManager，相当于启动了server
    poa = orb.resolve_initial_references("RootPOA")
    poa_manager = poa._get_the_POAManager()
    poa_manager.activate()

    # 创建并激活对象，对象的类从hello_POA中继承了激活的方法_this()
    lsh_impl = LshImpl()
    lsh_obj = lsh_impl._this()

    # 初始化命名服务对象
    name_service_obj = orb.resolve_initial_references("NameService")
    name_service_root = name_service_obj._narrow(CosNaming.NamingContext)
    assert name_service_root is not None, "Failed to narrow to NamingContext."

    # 将对象绑定到逻辑名"corbaInterface.Hello"
    service_name = [CosNaming.NameComponent("lsh", "Lsh")]
    name_service_root.bind(service_name, lsh_obj)
    print "Bound the lsh.Lsh Object to naming service"

    # 启动ORB
    print "Server is running"
    orb.run()